﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace SMplusXTeam.SyncMoped.SyncGurke
{
    public class SyncGurke
    {
        public DirectoryInfo SourceDirectory { get; set; }

        public DirectoryInfo BackupDirectory { get; set; }

        public DirectoryInfo VersioningDirectory { get; set; }

        public int NumberOfVersions { get; set; }

        public ComparisonMethod ComparisonMethod { get; set; }

        public void SynchronizeFiles()
        {
            DirectoryComparisonResult result = DirectoryComparison.CompareDirectories(SourceDirectory.FullName, BackupDirectory.FullName, ComparisonMethod);

            foreach (string filePath in result.NewFiles)
            {
                BackupFile(filePath);
            }

            foreach (string filePath in result.UnequalFiles)
            {
                BackupFile(filePath);
            }

            foreach (string filePath in result.DeletedFiles)
            {
                DeleteFile(filePath);
            }
        }

        private void DeleteFile(string filePath)
        {
            string fullFilePath = Path.Combine(BackupDirectory.FullName, filePath);
            FileHelper.DeleteFile(fullFilePath, BackupDirectory, NumberOfVersions, VersioningDirectory);
        }

        private void BackupFile(string filePath)
        {
            FileInfo file = new FileInfo(Path.Combine(SourceDirectory.FullName, filePath));
            string relativeFileDirectoryPath = FileHelper.GetRelativePath(file.DirectoryName, SourceDirectory.FullName);
            FileHelper.BackupFile(
                file.FullName,
                Path.Combine(BackupDirectory.FullName, relativeFileDirectoryPath),
                NumberOfVersions,
                Path.Combine(VersioningDirectory.FullName, relativeFileDirectoryPath)
            );
        }
    }
}
